package com.lushuan.ch11_springboot_test.utils;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

/**
 * 创建线程池 https://www.jianshu.com/p/94852bd1a283
 */
@Component
public class ThreadUtil {

    @Bean
    public ExecutorService getExecutorService() {
        return new ThreadPoolExecutor(20, 20, 3600, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2000));
    }

    // 1. 创建固定大小的线程池
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
    }
    // 2. 创建一个单线程的线程池
    public static ExecutorService newSingleThreadExecutor() {
        return new ThreadPoolExecutor(
                1, 1, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>()
        ) {
            // 确保在 shutdown 之后不再接受新任务
            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                super.afterExecute(r, t);
                if (t != null && !(t instanceof CancellationException)) {
                    // 处理异常
                    t.printStackTrace();
                }
            }

            @Override
            protected void terminated() {
                super.terminated();
                // 清理资源
                System.out.println("ThreadPool has been terminated.");
            }
        };
    }

    // 3. 创建一个可缓存线程池
    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>());
    }

    // 4. 创建一个定长线程池，支持定时及周期性任务执行
    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }

}